package org.itboys.store.service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import org.itboys.dto.ProductImage;
import org.itboys.mongodb.MongoUtils;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.oss.OssService;
import org.itboys.solr.client.SolrClient;
import org.itboys.store.cache.ProductDetailLoader;
import org.itboys.store.cache.ProductLoader;
import org.itboys.store.constant.ProductConstant;
import org.itboys.store.dto.ProductDetail;
import org.itboys.store.entity.Product;
import org.itboys.store.entity.ProductCount;
import org.itboys.store.search.ProductSearchDoc;
import org.itboys.store.search.ProductSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import org.springframework.web.multipart.MultipartFile;

@Service
public class StoreProductService extends BaseService<Product, Long>{
	
	private static final long serialVersionUID = 6480335544000649473L;


	@Resource(name = "ossService")
    OssService productOssService;

	@Resource(name = "productDS")
	private MongoDataSource ds;

	@Resource(name = "storeProductLoader")
	private ProductLoader productLoader;

	@Resource(name = "storeProductDetailLoader")
	private ProductDetailLoader productDetailLoader;
	@Resource(name = "storeProductSolrClient")
	private SolrClient productSolrClient;
	@Autowired
	private ProductSearchService productSearchService;

	@Autowired
	private StoreProductCategorySpecService storeProductCategorySpecService;
	@Autowired
	private StoreProductCategorySpecDetailService storeProductCategorySpecDetailService;
	@Autowired
	private StoreProductSpecService storeProductSpecService;
	@Autowired
	private StoreProductSpecDetailService storeProductSpecDetailService;
	@Autowired
	private StoreProductCountService storeProductCountService;

//	@Resource(name = "productSearchService")
//	private ProductSearchService productSearchService;
	
	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	@Override
	protected Class<Product> getEntityClass() {
		return Product.class;
	}

	/**
	 * 从海仓同步产品信息时要用到的更新接口
	 * @param list
     */
	public void batchUpdateNoId(List<Product> list){
		List<String> goodsIds = Lists.newArrayListWithExpectedSize(list.size()+1);
		goodsIds.add("-1");
		for (Product product:
			 list) {
			goodsIds.add(product.getGoodsId());
		}
		Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
		param.put("goodsId in", goodsIds);
		List<Product> products = super.list(param);
		List<Long> ids = Lists.newArrayListWithExpectedSize(products.size());
		for (Product product :products) {
			ids.add(product.getId());
			for (Product product1:list) {
				if(product.getGoodsId().equals(product1.getGoodsId())){
					product.setStore(product1.getStore());
					product.setPrice(product1.getPrice());
					product.setImgList(product1.getImgList());
					break;
				}
			}
		}
		super.batchUpdate(products);
		productDetailLoader.clearCache(ids);
	}

	/**
	 * 新增或修改
	 * @param product
	 * @return
	 */
	public boolean insert(Product product, MultipartFile imgFile, MultipartFile[] imgFiles){
		try{
			//组装商品主图
			String tempFile = null;
			if(imgFile != null && !imgFile.isEmpty()){
				tempFile = productOssService.upload(imgFile.getInputStream(), ProductConstant.ImgPath.OSS_PATH);
				product.setImageUrl(ProductConstant.OSS_URL_PREFIX + ProductConstant.ImgPath.OSS_PATH + "/" + tempFile);
			}
			if(imgFiles != null && imgFiles.length > 0){
				List<ProductImage> images = Lists.newArrayListWithExpectedSize(imgFiles.length);
				for (MultipartFile file : imgFiles) {
					if(file != null && !file.isEmpty()){
						String image = productOssService.upload(file.getInputStream(), ProductConstant.ImgPath.OSS_PATH);
						image = ProductConstant.OSS_URL_PREFIX + ProductConstant.ImgPath.OSS_PATH + "/" + image;
						ProductImage productImage = new ProductImage();
						productImage.setIMAGE_URL(image);
						images.add(productImage);
					}
				}
				product.setImgList(images);
			}

			if(product.getId() != 0){
				MongoUtils.fill(product, getById(product.getId()));
				update(product);
				//清空商品缓存
				productDetailLoader.clearCache(product.getId());
			}else{
				save(product);
				ProductCount productCount = new ProductCount();
				productCount.setProductId(product.getId());
				storeProductCountService.save(productCount);
			}
			productDetailLoader.clearCache(product.getId());
			final Long id = product.getId();
			ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor();//开启线程  往搜索引擎里加信息
			fixedThreadPool.execute(new Runnable(){
				@Override
				public void run() {
					try {
						productSolrClient.deleteDocument(id.toString());
						ProductDetail detail = productDetailLoader.get(id);
						ProductSearchDoc doc = new ProductSearchDoc();
						doc.setProductId(id);
						doc.setBrandId(detail.getBrandId());
						doc.setCategoryFullIdPath(detail.getCatId().toString());
						doc.setProductName(detail.getTitle() + ":::" + detail.getBrandName() + ":::" + detail.getCatName());
						doc.setPrice(detail.getRealPrice());
						doc.setSoldCount(detail.getSoldCount());
						doc.setReadCount(detail.getReadCount());
						doc.setType(detail.getType());
						productSearchService.buildProductSearchIndex(doc);
					} catch (Exception e) {
						logger.error("publishSupplyPush error", e);
					}
				}
			});
			return true;
		}catch(Exception e){
			logger.error("ProductService.save error", e);
		}
		return false;
	}

}
